<?php
/**
 * Created by PhpStorm.
 * User: 17274
 * Date: 2018/4/1
 * Time: 14:36
 */

namespace app\hook\behaviors;

use think\Config;
use think\Request;
use think\Route;
use think\Session;

class authBehavior
{
    /*
        * 单行为模式
        * 钩子权限验证
        * */
    public function run(&$params){
        $request=Request::instance();
        $controller = strtolower($request->controller());
        if ($controller != 'frontend' && !empty(Session::get("username")) && Session::get("username") != 'admin') {
            $auth_flag = false;
            $action = strtolower($request->action());
            //判定不用鉴权列表
            $no_auth_list = Config::get("app.no_auth_list");
            $no_auth_list = strtolower(json_encode($no_auth_list));
            $no_auth_list = json_decode($no_auth_list,true);
            foreach ($no_auth_list as $c=>$a){
                if ($controller == $c && in_array($action,$a)){
                    $auth_flag = true;
                    break;
                }
            }
            //继续验证权限
            if (!$auth_flag) {
                $acResource = Session::get("ac-resource");
                $acResource = strtolower(json_encode($acResource));
                $acResource = json_decode($acResource,true);
                if (!empty($acResource) && in_array($controller.'--'.$action,$acResource))
                    $auth_flag = true;
                //ajax请求
                if($request->isPost()){
                    if (!$auth_flag)
                        exit(json_encode(op_noper()));
                }
                //GET权限验证
                if(!$auth_flag){
                    exit(forbidden(js_css()));
                }
            }
        }
    }
}